#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
info() { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1" >&2; }

# 静默下载函数 (仅使用wget)
silent_download() {
    local url=$1
    local output=$2
    if [[ ! -f "$output" ]]; then
        if ! wget -q --show-progress=no -c "$url" -O "$output" &>/dev/null; then
            error "下载失败: $(basename "$output")"
            return 1
        fi
    fi
    return 0
}

# 检查是否为Arch系系统
check_arch() {
    info "检查系统兼容性..."
    if ! grep -q 'PRETTY_NAME=.*Arch Linux' /etc/os-release 2>/dev/null; then
        error "此脚本仅支持 Arch Linux"
        error "当前系统: $(grep '^PRETTY_NAME=' /etc/os-release | cut -d'"' -f2)"
        
        # 询问用户是否确认继续
        echo -e "${YELLOW}[WARNING]${NC} 检测到非Arch Linux系统，继续安装可能导致不可预知的问题"
        read -p "是否确认继续？(y/N): " confirm
        if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
            info "用户取消安装"
            exit 1
        fi
        
        warning "用户确认继续安装，请注意可能出现的兼容性问题"
        return 0
    fi
    success "系统兼容性检查通过"
}

# 检查root权限
check_root() {
    info "检查权限..."
    if [ "$(id -u)" -ne 0 ]; then
        error "请使用root用户或sudo运行此脚本"
        exit 1
    fi
    success "权限检查通过"
}

# 安装依赖
install_deps() {
    info "安装依赖包..."
    local deps=(
        xorg-server-xvfb gtk3 libnotify nss libxss libxtst 
        xdg-utils at-spi2-core libutil-linux libsecret 
        alsa-lib screen wget unzip jq ffmpeg dialog sudo
    )
    
    # 检查是否为Arch Linux系统
    if ! grep -q 'PRETTY_NAME=.*Arch Linux' /etc/os-release 2>/dev/null; then
        warning "非Arch Linux系统，跳过依赖安装"
        warning "请确保系统已安装以下依赖包: ${deps[*]}"
        
        # 询问用户是否继续
        read -p "是否继续安装？(y/N): " confirm
        if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
            info "用户取消安装"
            exit 1
        fi
        
        success "跳过依赖安装，继续执行"
        return 0
    fi
    
    # Arch Linux系统正常安装依赖
    pacman -Syu --noconfirm --needed "${deps[@]}" >/dev/null 2>&1 || {
        error "依赖安装失败"
        
        # 询问用户是否继续
        warning "依赖安装失败，继续安装可能导致功能异常"
        read -p "是否继续安装？(y/N): " confirm
        if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
            info "用户取消安装"
            exit 1
        fi
        
        warning "用户确认继续安装，请注意可能出现的功能问题"
        return 0
    }
    
    success "依赖安装完成"
}

# 安装QQ
install_qq() {
    info "准备安装QQ..."
    local QQ_DIR="/opt/QQ"
    
    case "$(uname -m)" in
        aarch64) os=arm64 ;;
        x86_64) os=x86_64 ;;
        *) error "不支持的架构: $(uname -m)"; exit 1 ;;
    esac

    # 检查是否已安装
    if [ ! -f "$QQ_DIR/qq" ]; then
        mkdir -p "$QQ_DIR"
        cd "$QQ_DIR"
        
        info "下载 QQNT AppImage..."
        local download_url="https://dldir1v6.qq.com/qqfile/qq/QQNT/Linux/QQ_3.2.19_250904_${os}_01.AppImage"
        local tmp_appimage="/tmp/QQNT.AppImage"
        
        if ! silent_download "$download_url" "$tmp_appimage"; then
            error "QQNT 下载失败"
            exit 1
        fi
        
        chmod +x "$tmp_appimage"
        info "提取 AppImage 到 /opt/QQ..."
        
        # 使用 --appimage-extract 到临时目录，然后移动文件到 /opt/QQ
        TMP_DIR=$(mktemp -d)
        cd "$TMP_DIR"
        
        if ! "$tmp_appimage" --appimage-extract &>/dev/null; then
            error "AppImage 提取失败"
            rm -rf "$TMP_DIR" "$tmp_appimage"
            exit 1
        fi
        
        # 移动文件到目标目录
        shopt -s dotglob
        mv squashfs-root/* "$QQ_DIR"/
        shopt -u dotglob
        
        # 清理临时文件
        rm -rf "$TMP_DIR" "$tmp_appimage" "$QQ_DIR/squashfs-root"
        
        # 创建启动链接
        ln -sf "$QQ_DIR/qq" /usr/local/bin/qq
        
    else
        info "QQNT 已经安装在 /opt/QQ，跳过下载和提取。"
    fi
    
    success "QQ安装完成"
}

# 安装NapCat
install_napcat() {
    info "准备安装NapCat..."
    local napcat_dir="/opt/QQ/resources/app/app_launcher/napcat"
    mkdir -p "$napcat_dir"
    local download_url="https://github.chenc.dev/https://github.com/NapNeko/NapCatQQ/releases/latest/download/NapCat.Shell.zip"
    local tmp_zip="/tmp/NapCat.Shell.zip"

    if ! silent_download "$download_url" "$tmp_zip"; then
        error "NapCat下载失败"
        exit 1
    fi

    info "正在配置NapCat..."
    if ! unzip -q "$tmp_zip" -d "$napcat_dir"; then
        error "NapCat解压失败"
        rm -f "$tmp_zip"
        exit 1
    fi
    rm -f "$tmp_zip"
    success "NapCat安装完成"
}

# 配置NapCat加载器
configure_napcat() {
    info "正在配置加载器..."
    cat > /opt/QQ/resources/app/loadNapCat.cjs << 'EOF'
const fs = require("fs");
const path = require("path");
const CurrentPath = path.dirname(__filename);
const hasNapcatParam = process.argv.includes("--no-sandbox");
if (hasNapcatParam) {
    (async () => {
        await import("file://" + path.join(CurrentPath, "./app_launcher/napcat/napcat.mjs"));
    })();
} else {
    require("./application/app_launcher/index.js");
    setTimeout(() => {
        global.launcher.installPathPkgJson.main = "./application.asar/app_launcher/index.js";
    }, 0);
}
EOF

    chmod -R 755 /opt/QQ >/dev/null 2>&1
    sed -i 's|"main": ".*/index.js"|"main": "./loadNapCat.cjs"|' /opt/QQ/resources/app/package.json
    success "加载器配置完成"
}

# 安装CLI工具
install_cli_tools() {
    info "正在安装命令行工具..."
    local base_url="https://github.chenc.dev/https://raw.githubusercontent.com/NapNeko/NapCat-TUI-CLI/main/script/tui-cli"
    local tools=("_napcat_Boot" "_napcat_Config" "_napcat_old" "napcat")
    local tmp_dir="/tmp/napcat_tools"
    
    mkdir -p "$tmp_dir"
    info "正在获取CLI工具..."
    
    for tool in "${tools[@]}"; do
        local tmp_tool="$tmp_dir/$tool"
        if ! silent_download "${base_url}/${tool}" "$tmp_tool"; then
            warning "工具下载失败: $tool"
            continue
        fi
        
        # 下载完成后修改文件内容
        if [[ -f "$tmp_tool" ]]; then
            # 修改路径配置
            sed -i \
                -e 's|TARGET_USER_HOME="$HOME"|TARGET_USER_HOME="/opt"|g' \
                -e 's|QQ_EXECUTABLE="$INSTALL_BASE_DIR/opt/QQ/qq"|QQ_EXECUTABLE="/opt/QQ/qq"|g' \
                -e 's|NAPCAT_DIR="$INSTALL_BASE_DIR/opt/QQ/resources/app/app_launcher/napcat"|NAPCAT_DIR="/opt/QQ/resources/app/app_launcher/napcat"|g' \
                -e 's|CONFIG_DIR="$INSTALL_BASE_DIR/opt/QQ/resources/app/app_launcher/napcat/config"|CONFIG_DIR="/opt/QQ/resources/app/app_launcher/napcat/config"|g' \
                "$tmp_tool"
        fi
        
        mv "$tmp_tool" "/usr/local/bin/${tool}"
        chmod +x "/usr/local/bin/${tool}"
    done
    rm -rf "$tmp_dir"
    success "命令行工具安装完成"
}

# 主函数
main() {
    echo -e "\n${GREEN}=== QQ & NapCat 安装脚本 ===${NC}\n"
    
    check_arch
    check_root
    install_deps
    install_qq
    install_napcat
    configure_napcat
    install_cli_tools
    
    echo -e "\n${GREEN}=== 安装完成 ===${NC}"
    echo -e "启动QQ: ${YELLOW}/opt/QQ/qq${NC}"
    echo -e "启动NapCat: ${YELLOW}napcat${NC}"
    echo -e "\n${BLUE}请尽情使用吧！${NC}\n"
}

# 执行主函数
main
